﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;

namespace LyncStatusChanger
{
	internal class Program
	{
		private static void Main(string[] args)
		{
			try
			{
				string quote = QuoteOfTheDay();
				var lyncManager = new LyncManager();
				lyncManager.ChangePersonalNote(quote);
			}
			catch (Exception ex)
			{
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine(ex.ToString());
			}
			finally
			{
				WriteToConsole("Press any key to exit", ConsoleColor.White);
				Console.Read();
			}
		}

		private static string _quoteTag = "inspirational";
		private static string QuoteTag
		{
			get { return _quoteTag; }
			set { _quoteTag = value; }
		}

		public static string QuoteSource { get
		{
			return string.Format(ConfigurationManager.AppSettings["quoteFeedURLFormat"]
			                     ?? @"http://www.quotesdaddy.com/feed/tagged/{0}", QuoteTag);
		} }

		private static string QuoteOfTheDay()
		{
			SetTag();
			string quote = string.Empty;
			var separator = new String('-', 8);
			do
			{
				var quoteDocument = XDocument.Load(QuoteSource);
				if (quoteDocument.Descendants("title").Count() == 1)
				{
					WriteErrorToScreen();
					continue;
				}
				var quoteBlock = quoteDocument.Descendants("title").Last();
				quote = quoteBlock.Value;
				WriteToConsole("\n" + separator);
				WriteToConsole(quote, ConsoleColor.White);

				WriteToConsole(separator + "\n");
				WriteToConsole("Set as Lync Status(y), Next(n), Change Tag(t), Quit(q)? (y/n/t/q)", ConsoleColor.Yellow);
			} while (ProcessQuote());
			return quote;
		}

		private static bool ProcessQuote()
		{
			var userInput = Console.ReadKey(true).Key;
			switch (userInput)
			{
				case ConsoleKey.Y:
					return false;
					break;
				case ConsoleKey.T:
					SetTag();
					return true;
					break;
				case ConsoleKey.N:
					return true;
					break;
				case ConsoleKey.Q:
					Environment.Exit(0);
					break;
				default:
					WriteToConsole("Invalid input. Please try again or press q to quit",ConsoleColor.Red);
					return ProcessQuote();
					break;
			}
			return true;
		}

		private static void SetTag()
		{
			WriteToConsole(String.Format("Provide Tag (leave blank for {0}):", QuoteTag), ConsoleColor.Magenta, false);
			var tag = Console.ReadLine();
			QuoteTag = String.IsNullOrWhiteSpace(tag) ? QuoteTag : tag;
		}
		private static void WriteErrorToScreen()
		{
			WriteToConsole("No quotes found", ConsoleColor.Red);
		}

		private static void WriteToConsole(string message, ConsoleColor consoleColor = ConsoleColor.Green, bool breakLine = true)
		{
			Console.ForegroundColor = consoleColor;
			if (breakLine)
				Console.WriteLine(message);
			else
				Console.Write(message);
			Console.ResetColor();
		}
	}
}